/**
 * 快递员 - 新增或编辑界面
 */
Ext.define("PSI.Express.ExpressMan.EditForm", {
	extend : "Ext.window.Window",
	config : {
		parentForm : null,
		entity : null
	},

	initComponent : function() {
		var me = this;
		var entity = me.getEntity();
		me.adding = entity == null;
		var buttons = [];
		if (!entity) {
			buttons.push({
						text : "保存并继续新增",
						formBind : true,
						handler : function() {
							var me = this;
							me.onOK(true);
						},
						scope : this
					});
		}

		buttons.push({
					text : "保存",
					formBind : true,
					iconCls : "PSI-button-ok",
					handler : function() {
						me.onOK(false);
					},
					scope : me
				}, {
					text : me.adding ? "关闭" : "取消",
					handler : function() {
						me.close();
					},
					scope : me
				});

		Ext.apply(me, {
					title : entity == null ? "新增快递员" : "编辑快递员",
					modal : true,
					resizable : false,
					onEsc : Ext.emptyFn,
					width : 560,
					height : 500,
					layout : "border",
					items : [{
						region : "north",
						height : 130,
						border : 0,
						layout : "fit",
						items : [{
							id : "editForm",
							xtype : "form",
							border : 0,
							layout : {
								type : "table",
								columns : 2
							},
							height : "100%",
							bodyPadding : 5,
							defaultType : 'textfield',
							fieldDefaults : {
								labelWidth : 90,
								labelAlign : "right",
								labelSeparator : "",
								msgTarget : 'side'
							},
							items : [{
								xtype : "hidden",
								name : "id",
								value : entity == null ? null : entity
										.get("id")
							}, {
								id : "editName",
								fieldLabel : "姓名",
								allowBlank : false,
								blankText : "没有输入姓名",
								beforeLabelTextTpl : PSI.Const.REQUIRED,
								name : "name",
								value : entity == null ? null : entity
										.get("name"),
								listeners : {
									specialkey : {
										fn : me.onEditSpecialKey,
										scope : me
									}
								},
								width : 250
							}, {
								id : "editMobile",
								fieldLabel : "手机号",
								allowBlank : false,
								blankText : "没有输入手机号",
								beforeLabelTextTpl : PSI.Const.REQUIRED,
								name : "mobile",
								value : entity == null ? null : entity
										.get("mobile"),
								listeners : {
									specialkey : {
										fn : me.onEditSpecialKey,
										scope : me
									}
								},
								width : 250
							}, {
								id : "editBindCode",
								fieldLabel : "绑定微信校验码",
								name : "bindCode",
								value : entity == null ? null : entity
										.get("bindCode"),
								listeners : {
									specialkey : {
										fn : me.onEditLastSpecialKey,
										scope : me
									}
								},
								width : 250
							}, {
								xtype : "displayfield",
								value : "如果验证码不填写，后台就自动把手机号作为校验码"
							}, {
								xtype : 'fieldcontainer',
								fieldLabel : '状态',
								labelWidth : 80,
								defaultType : 'radiofield',
								colspan : 2,
								width : 200,
								defaults : {
									flex : 1
								},
								layout : 'hbox',
								items : [{
											boxLabel : '启用',
											name : 'enabled',
											inputValue : '1',
											id : 'radioUse'
										}, {
											boxLabel : '停用',
											name : 'enabled',
											inputValue : '0',
											id : 'radioStop'
										}]
							}, {
								xtype : "hidden",
								name : "districtList",
								id : "hiddenDistrict"
							}]
						}]
					}, {
						region : "center",
						layout : "fit",
						border : 0,
						items : [me.getMainGrid()]
					}],
					buttons : buttons,
					listeners : {
						show : {
							fn : me.onWndShow,
							scope : me
						},
						close : {
							fn : me.onWndClose,
							scope : me
						}
					}
				});

		me.callParent(arguments);

		me.editName = Ext.getCmp("editName");
		me.editMobile = Ext.getCmp("editMobile");
		me.editBindCode = Ext.getCmp("editBindCode");

		me.radioUse = Ext.getCmp("radioUse");
		me.radioStop = Ext.getCmp("radioStop");

		me.hiddenDistrict = Ext.getCmp("hiddenDistrict");

		me.editForm = Ext.getCmp("editForm");

		me.__editorList = [me.editName, me.editMobile, me.editBindCode];
	},

	onWndShow : function() {
		var me = this;

		var edit = me.editName;
		edit.focus();
		edit.setValue(edit.getValue());

		if (me.getEntity()) {
			// 编辑
			var enabled = me.getEntity().get("status") == 1;
			me.radioUse.setValue(enabled);
			me.radioStop.setValue(!enabled);

			var el = me.getEl();
			el.mask(PSI.Const.LOADING);
			Ext.Ajax.request({
						url : PSI.Const.BASE_URL
								+ "Home/Express/expressManInfo",
						params : {
							id : me.getEntity().get("id")
						},
						method : "POST",
						callback : function(options, success, response) {
							if (success) {
								var data = Ext.JSON
										.decode(response.responseText);

								var store = me.getMainGrid().getStore();
								store.removeAll();
								store.add(data.districtList);
							}

							el.unmask();
						}
					});
		} else {
			me.radioUse.setValue(true);
			me.radioStop.setValue(false);
		}
	},

	onWndClose : function() {
		var me = this;
		if (me.__lastId) {
			if (me.getParentForm()) {
				me.getParentForm().refreshEditResult(me.__lastId);
			}
		}
	},

	onOK : function(thenAdd) {
		var me = this;

		var store = me.getMainGrid().getStore();
		var districtList = [];
		for (var i = 0; i < store.getCount(); i++) {
			districtList.push(store.getAt(i).get("id"));
		}
		me.hiddenDistrict.setValue(districtList.join(","));

		var f = me.editForm;
		var el = f.getEl();
		el.mask(PSI.Const.SAVING);
		f.submit({
					url : PSI.Const.BASE_URL + "Home/Express/editExpressMan",
					method : "POST",
					success : function(form, action) {
						el.unmask();
						me.__lastId = action.result.id;
						PSI.MsgBox.tip("数据保存成功");
						me.focus();
						if (thenAdd) {
							me.clearEdit();
						} else {
							me.close();
						}
					},
					failure : function(form, action) {
						el.unmask();
						PSI.MsgBox.showInfo(action.result.msg, function() {
									me.editName.focus();
								});
					}
				});
	},

	onEditSpecialKey : function(field, e) {
		var me = this;

		if (e.getKey() === e.ENTER) {
			var id = field.getId();
			for (var i = 0; i < me.__editorList.length; i++) {
				var editorId = me.__editorList[i].getId();
				if (id === editorId) {
					var edit = me.__editorList[i + 1];
					edit.focus();
					edit.setValue(edit.getValue());
				}
			}
		}
	},

	onEditLastSpecialKey : function(field, e) {
		var me = this;
		if (e.getKey() == e.ENTER) {
			if (me.editForm.getForm().isValid()) {
				me.onOK(me.adding);
			}
		}
	},

	clearEdit : function() {
		var me = this;

		me.editName.focus();

		var editors = [me.editName, me.editMobile];
		for (var i = 0; i < editors.length; i++) {
			var edit = editors[i];
			if (edit) {
				edit.setValue(null);
				edit.clearInvalid();
			}
		}

		me.getMainGrid().getStore().removeAll();
	},

	getMainGrid : function() {
		var me = this;

		if (me.__mainGrid) {
			return me.__mainGrid;
		}

		var modelName = "PSI_Express_ExpressMan_EditForm_PSIExpressManDistrict";
		Ext.define(modelName, {
					extend : "Ext.data.Model",
					fields : ["name"]
				});
		var store = Ext.create("Ext.data.Store", {
					autoLoad : false,
					model : modelName,
					data : []
				});

		me.__mainGrid = Ext.create("Ext.grid.Panel", {
					title : "所属片区",
					viewConfig : {
						enableTextSelection : true
					},
					columnLines : true,
					margin : 5,
					tbar : [{
								text : "新增片区",
								iconCls : "PSI-button-add",
								handler : me.onAddDistrict,
								scope : me
							}],
					columns : [{
								header : "片区",
								dataIndex : "name",
								menuDisabled : true,
								sortable : false,
								flex : 1
							}, {
								header : "",
								id : "columnActionDelete",
								align : "center",
								menuDisabled : true,
								draggable : false,
								width : 40,
								xtype : "actioncolumn",
								items : [{
									icon : PSI.Const.BASE_URL
											+ "Public/Images/icons/delete.png",
									handler : function(grid, row) {
										var store = grid.getStore();
										store.remove(store.getAt(row));
										if (store.getCount() == 0) {
											store.add({});
										}
									},
									scope : me
								}]
							}],
					store : store
				});

		return me.__mainGrid;
	},

	onAddDistrict : function() {
		var me = this;

		var form = Ext.create("PSI.Express.ExpressMan.DistrictSelectForm", {
					parentForm : me
				});
		form.show();
	},

	setDistrictInfo : function(items) {
		var me = this;
		var store = me.getMainGrid().getStore();
		for (var i = 0; i < items.length; i++) {
			var district = items[i];
			store.add({
						id : district.get("id"),
						name : district.get("name")
					});
		}
	}
});